//
//  MYAgreementViewController.m
//  投融保
//
//  Created by 523 on 13-12-20.
//  Copyright (c) 2013年 木叶科技. All rights reserved.
//

#import "MYAgreementViewController.h"
#import "MYBankCell.h"
#import "UIImageView+WebCache.h"

@interface MYAgreementViewController ()

@end

@implementation MYAgreementViewController

@synthesize bindingService,districtService;
@synthesize arrCards,bankTable;
@synthesize arrLocation,arrProvince,arrCitylist;
@synthesize locationPicker;

extern NSString *realName; //真实姓名
extern NSDictionary *userInformation ;//用户信息
extern NSDictionary *bankDic; //支持银行
extern NSString *key;

NSString *bankCode;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLocationDict:) name:@"getAsyData" object:nil];
    
    // Do any additional setup after loading the view from its nib.
    self.txtCityName.leftView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 44)];
    self.txtCityName.leftViewMode=UITextFieldViewModeAlways;
    self.txtCardID.leftView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 44)];
    self.txtCardID.leftViewMode=UITextFieldViewModeAlways;
    
    int offSet_y=200;
    if (SCREEN_HEIGHT>480) {
        offSet_y=100;
    }
    [self.bgScrollView setContentSize:CGSizeMake(320, SCREEN_HEIGHT+offSet_y)];
    
    // 设置默认值
    if (!userInformation) {
        self.txtUsername.text=realName;
    }else
    {
        self.txtUsername.text=[userInformation valueForKey:@"realName"];
        if (![[userInformation valueForKey:@"certNo"] isEqual:[NSNull null]]) {
            self.txtUserIDNo.text=[userInformation valueForKey:@"certNo"];
        }
        
    }
    self.bindingService =[MYWebService new]; //绑卡请求
    self.districtService=[MYWebService new];  //获取地名请求
    self.arrLocation=[NSMutableArray new];
    self.arrProvince=[NSMutableArray new];
    
    NSString *strAppGetAllDistrictService=@"service=appGetAllDistrictService";
    //获取省市地名
    [self.districtService getDataAsynWithKey:key encryptedString:strAppGetAllDistrictService appKey:nil];
    
    //银行选择数组
    self.arrCards=[NSMutableArray new];
    self.arrCards = [[JsonParse new] bankCardPares:bankDic];
    
    [self.imageBank setImageWithURL:[NSURL URLWithString:[[self.arrCards objectAtIndex:0] logoUrl]]];
    
    locationPicker=[UIPickerView new];
    locationPicker.delegate=self;
    locationPicker.dataSource=self;
    [self.txtCityName setInputView:locationPicker];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)endEditing:(UITextField *)sender {
    [self.view endEditing:YES];
    [self.bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

//选择银行卡
- (IBAction)btnChoosBank:(UIButton *)sender {
    if (sender.selected) {
        sender.selected=NO;
        [self.bankTable removeFromSuperview];
        return;
    }else
    {
        sender.selected=YES;
        if (!self.bankTable) {
            self.bankTable =[[UITableView alloc] init];
            [self.bankTable setFrame:CGRectMake(34, self.btnBank.frame.origin.y+80, 300, 400)];
        }
        [UIView animateWithDuration:0.25 animations:^{
            self.bankTable.alpha=1;
        }];
        
        [self.bankTable setDataSource:self];
        [self.bankTable setDelegate:self];
        [self.bankTable.layer setCornerRadius:5];
        [self.bankTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        self.bankTable.alpha=0;
        [self.bgScrollView addSubview:self.bankTable];
        
        [UIView animateWithDuration:0.25 animations:^{
            self.bankTable.alpha=1;
        }];
    }
    
    
    
}
//返回事件
- (IBAction)btnReturn:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


//选中已阅读协议事件
- (IBAction)btnAgreement:(UIButton *)sender {
    if (sender.selected) {
        [sender setImage:[UIImage imageNamed:@"disagreed_icon"] forState:UIControlStateNormal];
        sender.selected=!sender.selected;
        
        
    }
    else
    {
        [sender setImage:[UIImage imageNamed:@"agreed_icon"] forState:UIControlStateSelected];
        sender.selected=!sender.selected;
    }
    
}

//绑卡事件
- (IBAction)btnNextStep:(UIButton *)sender {
    
    NSString *strResultInfo;
    
    if (!self.btnProtocle.selected) {
        
        strResultInfo=@"您需要同意服务条款";
        
    }
    else
    {
        //    NSString *strAddBankCardService=@"service=addBankCardService&bankOpenName=新疆&bankCardNo=8888888888888888&bankCode=CITIC&bankProvince=重庆市&bankCity=重庆市";
        NSString *strAddBankCardService=[NSString stringWithFormat:@"service=addBankCardService&bankOpenName=%@&bankCardNo=%@&bankCode=%@&bankProvince=%@&bankCity=%@",self.txtUsername.text,self.txtCardID.text,bankCode,provinceName,cityName];
        
        [self.bindingService getDataSynWithKey:key encryptedString:strAddBankCardService appKey:nil];
        strResultInfo=[[self.bindingService.profileDataSyn valueForKey:@"result"]valueForKey:@"code"];
        
        strResultInfo=[[self.bindingService.profileDataSyn valueForKey:@"result"]valueForKey:@"message"];
        
    }
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:strResultInfo delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    
    
}




#pragma mark ----------- text delegate---------------

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    //正则表达式验证
    switch (textField.tag) {
            
        case 534://银行卡号
        {
            if (textField.text.length<19&&textField.text.length>16) {
                NSRegularExpression *regular=[NSRegularExpression regularExpressionWithPattern:@"^[0-9]+$" options:0 error:nil];
                NSTextCheckingResult *result = [regular firstMatchInString:textField.text options:0 range:NSMakeRange(0, textField.text.length)];
                if (!result) {
                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"银行卡号为位数字" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }
            else{
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"银行卡号长度为16～19位" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
            }
            
        }
            break;
            
        default:
            break;
    }
}


#pragma mark -------------pickerView delegate-------------------
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component==0) {
        return self.arrProvince.count;
    }else
    {
        return arrCitylist.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component==0) {
        return [self.arrProvince objectAtIndex:row];
    }else
    {
        return [arrCitylist objectAtIndex:row];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component==0) {
        //除非有十足把握，否则请勿轻易改动
        NSArray *arrtemp=[[arrLocation objectAtIndex:row] valueForKey:@"cityList"];
        [arrCitylist removeAllObjects];
        for (int i=0; i<arrtemp.count; i++) {
            [arrCitylist addObject:[[arrtemp objectAtIndex:i] valueForKey:@"cityName"]];
        }
        //        NSLog(@"%@",arrCitylist);
        [locationPicker reloadComponent:1];
        provinceName=[arrProvince objectAtIndex:row];
    }
    else
    {
        cityName=[arrCitylist objectAtIndex:row];
        if (provinceName) {
            self.txtCityName.text=[NSString stringWithFormat:@"%@%@",provinceName,cityName];
        }
    }
}




#pragma mark ----------------tableView 协议————————————————————————————


- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.arrCards.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier=@"reuserIdentifier";
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    [cell.imageView setImageWithURL:[NSURL URLWithString:[[self.arrCards objectAtIndex:indexPath.row] logoUrl]] placeholderImage:nil];
    //设置背景
    [cell setBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_bg" ]]];
    cell.userInteractionEnabled=YES;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.imageBank setImageWithURL:[NSURL URLWithString:[[self.arrCards objectAtIndex:indexPath.row] logoUrl]]];
    bankCode= [[self.arrCards objectAtIndex:indexPath.row] bankCode];
    [UIView animateWithDuration:0.25 animations:^{
        self.btnBank.selected=NO;
        self.bankTable.alpha=0;
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}


//接收通知事件
- (void)getLocationDict:(NSNotification *)notify
{
    arrLocation=[[self.districtService.profileDataAsyn valueForKey:@"result"] valueForKey:@"data"];
    arrProvince=[[NSMutableArray alloc] init];
    arrCitylist=[[NSMutableArray alloc] init];
    
    for (int i=0; i<arrLocation.count; i++) {
        [self.arrProvince addObject:[[arrLocation objectAtIndex:i] valueForKey:@"provinceName"]];
    }
    NSArray *arrtemp=[[arrLocation objectAtIndex:0] valueForKey:@"cityList"];
    for (int i=0; i<arrtemp.count; i++) {
        [arrCitylist addObject:[[arrtemp objectAtIndex:i] valueForKey:@"cityName"]];
    }
    //    NSLog(@"+++++++++++++++++++%@",arrCitylist);
}

#pragma mark-   -----------状态栏底色------
- (UIStatusBarStyle)preferredStatusBarStyle
{
    [self.view setBackgroundColor:[UIColor blackColor]];
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden
{
    return NO;
}
@end
